#!/bin/bash

set -x

# default to update source then build

TOP_DIR=$(pwd)
SRC_DIR=$TOP_DIR/lib_source
BD_DIR=$TOP_DIR/lib_build
BIN_DIR=$TOP_DIR/lib_bin

export PATH=$TOP_DIR/cross/bin:$PATH

# export MAKE_OPT="-j 2"

cmd=all64
if [ -n "$1" ] ; then
	cmd=$1
fi

if [ "$cmd" == "all64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "update" ] ; then
	mkdir -p $SRC_DIR || exit 0
	cd $SRC_DIR
	if [ ! -d apr-1.3.9 ] ; then
		wget http://apache.freelamp.com/apr/apr-1.3.9.tar.bz2
		tar xjf apr-1.3.9.tar.bz2
	fi
	if [ ! -d apr-util-1.3.9 ] ; then
		wget http://apache.freelamp.com/apr/apr-util-1.3.9.tar.bz2
		tar xjf apr-util-1.3.9.tar.bz2
	fi
	if [ ! -d apr-iconv-1.2.1 ] ; then
		wget http://apache.freelamp.com/apr/apr-iconv-1.2.1.tar.bz2
		tar xjf apr-iconv-1.2.1.tar.bz2
	fi
	cd ..
fi


if [ "$cmd" == "all64" ] || [ "$cmd" == "b64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
	HOST_FLAG="--host=x86_64-w64-mingw32"
	ENV_FLAG='ac_cv_sizeof_ssize_t=8 ac_cv_sizeof_size_t=8 ssize_t_fmt=lld size_t_fmt=lld ac_cv_sizeof_off_t=4'
	if [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
		HOST_FLAG="--host=i686-w64-mingw32"
		ENV_FLAG='ac_cv_sizeof_ssize_t=4 ac_cv_sizeof_size_t=4 ssize_t_fmt=ld size_t_fmt=ld ac_cv_sizeof_off_t=4'
	fi
	rm -rf $BIN_DIR/apr
	mkdir -p $BD_DIR
	cd $BD_DIR
	rm -rf bd_apr bd_apr_util bd_apr_iconv
	# <1> build apr
	mkdir bd_apr
	cd bd_apr	
	CFLAGS="-O2" $SRC_DIR/apr-1.3.9/configure $HOST_FLAG --prefix=$BIN_DIR/apr \
			--enable-lfs \
			--enable-static --disable-shared \
			$ENV_FLAG
			
	# TODO : unable to build shared library, libtool complain undefined symbol
	# --disable-static --enable-shared \
	# --enable-static --disable-shared \

	make $MAKE_OPT
	make install
	cd ..

 	# <2> build apr-util
	mkdir bd_apr_util
	cd bd_apr_util
	$SRC_DIR/apr-util-1.3.9/configure $HOST_FLAG --prefix=$BIN_DIR/apr --with-apr=$BIN_DIR/apr
	( cd xml/expat/lib ; patch -p0 < $TOP_DIR/patch/apr_util_xml_expat.patch ; cd ../../.. )
	make $MAKE_OPT
	make install
	cd ..
	# <3> build apr-iconv
	mkdir bd_apr_iconv
	cd bd_apr_iconv
	patch -d $SRC_DIR/apr-iconv-1.2.1/include -p0 < $TOP_DIR/patch/apr_iconv_static.patch
	$SRC_DIR/apr-iconv-1.2.1/configure $HOST_FLAG --prefix=$BIN_DIR/apr --with-apr=$BIN_DIR/apr
	make $MAKE_OPT
	make install
	patch -d $SRC_DIR/apr-iconv-1.2.1/include -p0 -R < $TOP_DIR/patch/apr_iconv_static.patch
	mv $BIN_DIR/apr/bin/apriconv $BIN_DIR/apr/bin/apriconv.exe
	cd ..

	cd ..
fi

